﻿Imports System.IO
Imports System.Net
Imports System.Xml
Imports AutoClient.dllLib

Module ModPub
    Sub Main()
        ' 配置文件路径
        ' 获取当前执行文件的目录，并构建配置文件路径
        Dim configFilePath As String = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AutoUpdater.config")
        '//如果不存在时
        Dim strconfig As String =configFilePath.Replace("/","\")
        If Not File.Exists(strconfig) Then
            Dim dlgconfig As New Frmconfig
            With dlgconfig
                .StartPosition = FormStartPosition.CenterParent
                .ShowDialog()
                .Dispose()
            End With
            end 
        End If
        ' 创建一个XmlDocument对象并加载配置文件
        Dim xmlDoc As New XmlDocument()
        xmlDoc.Load(configFilePath)

        ' 读取根节点
        Dim rootNode As XmlNode = xmlDoc.DocumentElement

        ' 读取ServerUrl和UpdateFile值
        Dim serverUrl As String = GetNodeValue(rootNode, "ServerUrl")
        Dim strUpdateZipFile As string=GetNodeValue(rootNode,"UpdateZipFile")'更新文件地址
        Dim updateFile As String = GetNodeValue(rootNode, "UpdateFileName")

        ' 查询特定的 XML 元素并添加到字典
        Dim strAppName As String = GetNodeValue(rootNode, "AppName")
        Dim strAppFrom As String = GetNodeValue(rootNode, "AppFrom")
        Dim strOpenAppName As String = GetNodeValue(rootNode, "OpenApp")
        ' 使用 VersionChecker 类检查更新
        Dim versionChecker As New VersionChecker()
        Dim strlocalversion As String= System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "local_version.txt")
        If Not File.Exists(strlocalversion) Then
            File.WriteAllText("local_version.txt", "1.0.0.0")'初始化
        End If
        If versionChecker.CheckForUpdates(serverUrl, strlocalversion) Then
          ’  Console.WriteLine("有新版本可用。")
            ' 在这里你可以添加处理更新的逻辑
            Dim obj As New DownloadProgress ' DownloadConfirm
            With obj
                .AppFrom =$"本地版本：{versionChecker.NLocalVersion}" 
                .AppName =$"{strAppName},服务器最新版本:{versionChecker.NServerVersion}"
                .ServerVersionUrl =serverUrl'version.txt服务器地址
                .UpdateZipFile =strUpdateZipFile '更新文件update.zip地址
                .ShowDialog()
                .Dispose()
            End With
        Else
            Process.Start($"{strOpenAppName}.exe")
            Application.Exit()
        End If

        ' 结束程序
        End
        
    End Sub
    ' 辅助方法：从指定的父节点中获取子节点的值
    Private Function GetNodeValue(parentNode As XmlNode, nodeName As String) As String
        Dim node As XmlNode = parentNode.SelectSingleNode(nodeName)
        Return If(node IsNot Nothing, node.InnerText, String.Empty)
    End Function

End Module
